﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Threading;

namespace RVBike
{
    /// <summary>
    /// Interaction logic for MultiplePlayerPage.xaml
    /// </summary>
    public partial class MultiplePlayerPage : UserControl, ISwitchable
    {
        private List<RVRoom> _rooms;    // Room list for last reshresh result

        public MultiplePlayerPage()
        {
            InitializeComponent();

            _rooms = new List<RVRoom>();
            ListBox_room.Items.Clear();

            txt_user_name.Text = UserSetting.Instance().UserName;
            
            // Initialize multilanguage strings
            dummy_lan.Content = MultiLanguage.Instance().Translate("lan_game");
            dummy_inter.Content = MultiLanguage.Instance().Translate("internet_game");
            btn_join.Content = MultiLanguage.Instance().Translate("join");
            btn_join_inter.Content = MultiLanguage.Instance().Translate("join");
            btn_refresh.Content = MultiLanguage.Instance().Translate("refresh");
            btn_refresh_inter.Content = MultiLanguage.Instance().Translate("refresh");
            btn_create.Content = MultiLanguage.Instance().Translate("create");
            btn_back.Content = MultiLanguage.Instance().Translate("back");
        }

        private void OnButtonClick(object sender, RoutedEventArgs e)
        {
            if (sender == btn_back)
            {
                RVSwitcher.Switch(new MainPage());
            }
			else if (sender == btn_create)
			{
				RVSwitcher.Switch(new SinglePlayerPage(true));
			}
			else if (sender == btn_join)
			{
				RVRoom room = _rooms[ListBox_room.SelectedIndex];
                if (room.CurrentUser < room.MaxUser)
                {
                    string userName = "Unknown";

                    if (RVGameController.Instance().JoinRoom(userName, room.ServerIP, room.MCastIP))
                    {
                        GameSetting gs = new GameSetting();
                        switch (room.Mode)
                        {
                            case RVNetworkEnv.GAME_MODE_NORMAL: gs.GameMode = GameMode.Normal; break;
                            case RVNetworkEnv.GAME_MODE_MILEAGE: gs.GameMode = GameMode.Mileage; break;
                            case RVNetworkEnv.GAME_MODE_TIME: gs.GameMode = GameMode.Time; break;
                        }

                        gs.GameType = GameType.Lan;
                        gs.SelectedStage = StageManager.Instance().GetStage(room.MapName);

                        RVSwitcher.Switch(new RoomPage(), gs);
                    }
                }
			}
			else if (sender == btn_refresh)
			{
                RefreshRoomList();
			}
        }

        private void OnNewRoomReported(RVRoom room)
        {
            string text = String.Format("{0} - {1} [{2}, {3}] ({4}/{5})",
                       room.MapName, room.RoomName, room.ServerIP, room.MCastIP, room.CurrentUser, room.MaxUser);

            _rooms.Add(room);

            ListBox_room.Dispatcher.Invoke(new Action(() =>
                {
                    System.Diagnostics.Trace.WriteLine("UI update list box");
                    ListBox_room.Items.Add(text);
                }));
        }

        private void RefreshRoomList()
        {
            // Disable refresh button to avoid reentrant
            btn_refresh.IsEnabled = false;
            btn_join.IsEnabled = false;

            ListBox_room.Items.Clear();

            RVBike.RVRDP rdp = new RVBike.RVRDP(1000);  // Search 1 seconds
            rdp.NewRoom += OnNewRoomReported;

            Thread searchWorker = new Thread(() =>
            {
                _rooms = rdp.QueryRoom();
                rdp.NewRoom -= OnNewRoomReported;
                rdp.Close();
                rdp = null;
                
                btn_refresh.Dispatcher.Invoke(new Action(() => btn_refresh.IsEnabled = true));

                if (_rooms.Count > 0)
                {
                    btn_join.Dispatcher.Invoke(new Action(() => btn_join.IsEnabled = true));
                    ListBox_room.Dispatcher.Invoke(new Action(() => ListBox_room.SelectedIndex = 0));
                }
            });

            searchWorker.Start();
        }

        #region ISwitchable Members
        public void UtilizeState(object state)
        {
            throw new NotImplementedException();
        }

        public void WindowLocationChanged(double x, double y)
        {
        }
        #endregion

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            RefreshRoomList();
        }

    }
}
